package com.ntschy.web.controller.sys;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ntschy.common.constant.HttpStatus;
import com.ntschy.common.core.AjaxPageResult;
import com.ntschy.common.core.AjaxResult;
import com.ntschy.common.core.controller.BaseController;
import com.ntschy.common.core.entity.dataobject.SysMenu;
import com.ntschy.common.core.entity.dataobject.SysRole;
import com.ntschy.common.core.model.LoginUser;
import com.ntschy.common.utils.ServletUtils;
import com.ntschy.framework.service.SysPermissionService;
import com.ntschy.framework.service.TokenService;
import com.ntschy.sys.entity.dto.role.SysRoleAddUpdateDTO;
import com.ntschy.sys.entity.dto.role.SysRolePageDTO;
import com.ntschy.sys.entity.mapstruct.SysRoleMapstruct;
import com.ntschy.sys.service.ISysMenuService;
import com.ntschy.sys.service.ISysRoleService;
import com.ntschy.sys.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ezreal_geng
 */
@RestController
@RequestMapping("/sys/role")
@Api(tags = "角色接口")
@Validated
public class SysRoleController extends BaseController {

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private ISysUserService userService;

    // * ================================================基础增删改查BEGIN============================================= *
    @ApiOperation(value = "查询角色列表", notes = "")
    @ApiImplicitParam(name = "queryDto", value = "菜单列表查询实体类", required = true, dataType = "SysRolePageDTO")
    //@PreAuthorize("@ss.hasPermi('sys:role:page')")
    @PostMapping("/pageRole")
    public AjaxPageResult<SysMenu> pageRole(@RequestBody SysRolePageDTO pageDTO) {
        Page<SysMenu> page = PageHelper.startPage(pageDTO.getCurrPage(), pageDTO.getPageSize());
        SysRole queryRole = SysRoleMapstruct.SYS_ROLE_MAP_STRUCT.pageDtoToDo(pageDTO);
        List<SysRole> list = roleService.pageRole(queryRole);
        return buildPageResult(list, page);
    }

    @ApiOperation(value = "根据角色ID获取角色详情", notes = "")
    @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "String")
    //@PreAuthorize("@ss.hasPermi('sys:role:detail')")
    @GetMapping("/fetchRole")
    public AjaxResult<Map<String, Object>> fetchRole(@NotBlank(message = "角色ID不能为空") @Length(min = 36, max = 36, message = "角色ID不合法") String roleId) {
        // TODO 菜单
        SysMenu queryMenu = new SysMenu();
        List<SysMenu> menus = menuService.pageMenu(queryMenu);
        Map<String, Object> map = new HashMap<>();
        map.put("checkedKeys", menuService.listMenuIdByRoleId(roleId));
        map.put("menus", menuService.buildMenuTreeSelect(menus));
        map.put("role", roleService.fetchRole(roleId));
        return AjaxResult.success("获取角色详情成功", map);
    }

    @ApiOperation(value = "新增角色", notes = "")
    @ApiImplicitParam(name = "addDto", value = "新增角色实体类", required = true, dataType = "SysRoleAddUpdateDTO")
    //@PreAuthorize("@ss.hasPermi('sys:role:add')")
    @PostMapping("/addMenu")
    public AjaxResult<String> addMenu(@RequestBody SysRoleAddUpdateDTO addDto) {
        if(roleService.checkRoleNameExist(addDto.getName())) {
            return AjaxResult.error(HttpStatus.BAD_REQUEST, "角色名已存在");
        } else if(roleService.checkRoleKeyExist(addDto.getRoleKey())) {
            return AjaxResult.error(HttpStatus.BAD_REQUEST, "角色标示已存在");
        }
        SysRole addRole = SysRoleMapstruct.SYS_ROLE_MAP_STRUCT.addUpdateDtoToDo(addDto);
        return toAjax(roleService.addRole(addRole), "新增角色成功", "新增角色失败");
    }

    @ApiOperation(value = "更新角色", notes = "")
    @ApiImplicitParam(name = "updateDto", value = "更新角色实体类", required = true, dataType = "SysRoleAddUpdateDTO")
    //@PreAuthorize("@ss.hasPermi('sys:role:update')")
    @PostMapping("/updateMenu")
    public AjaxResult<String> updateMenu(@RequestBody SysRoleAddUpdateDTO updateDto) {
        if(roleService.checkRoleNameExist(updateDto.getName())) {
            return AjaxResult.error(HttpStatus.BAD_REQUEST, "角色名已存在");
        } else if(roleService.checkRoleKeyExist(updateDto.getRoleKey())) {
            return AjaxResult.error(HttpStatus.BAD_REQUEST, "角色标示已存在");
        }
        SysRole updateRole = SysRoleMapstruct.SYS_ROLE_MAP_STRUCT.addUpdateDtoToDo(updateDto);
        if(roleService.updateRole(updateRole) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (ObjectUtil.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
                loginUser.setPermissions(sysPermissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.fetchUserDetailByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return AjaxResult.success("更新角色成功");
        } else {
            return AjaxResult.error(HttpStatus.BAD_REQUEST, "更新角色失败");
        }
    }

    @ApiOperation(value = "根据角色ID删除角色", notes = "")
    @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "String")
    //@PreAuthorize("@ss.hasPermi('sys:role:delete')")
    @GetMapping("/deleteRole")
    public AjaxResult<String> deleteRole(@NotBlank(message = "菜单ID不能为空") @Length(min = 36, max = 36, message = "菜单ID不合法") String roleId) {
        return toAjax(roleService.deleteRole(roleId), "删除角色成功", "删除角色失败");
    }
    // * =================================================基础增删改查END============================================== *
}
